//
//  ReleaseCarvehicleViewController.m
//  Logistics
//
//  Created by hy002 on 2018/1/19.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "ReleaseCarvehicleViewController.h"
#import "CloseGoodsAddressViewController.h"
#import "GSPickerView.h"
#import "DateTimePickerView.h"
#import "ReleaseNotesViewController.h"

static NSString *cellPath = @"ReleaseCarvehicleCell";
@interface ReleaseCarvehicleViewController ()<UITableViewDelegate,UITableViewDataSource,DateTimePickerViewDelegate>
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)NSString *shipmentID;
@property (nonatomic, strong)NSString *shipmentText;
@property (nonatomic, strong)NSString *destinationID;
@property (nonatomic, strong)NSString *destinationText;
@property (nonatomic, strong)NSString *dayStr;
@property (nonatomic, strong)NSString *timeStr;
@property (nonatomic, assign)BOOL isGx;
@property (nonatomic, strong)GSPickerView *pickerView;
@property (nonatomic, strong)DateTimePickerView *datePickerView;

@end

@implementation ReleaseCarvehicleViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _shipmentID = @"";
    _shipmentText = @"选择我将要卸货的地址";
    _destinationID = @"";
    _destinationText = @"选择我将要返回的地址";
    _dayStr = @"";
    _timeStr = @"";
    [self creatUI];
    
}

- (void)creatUI
{
    self.navigationItem.title = @"发布回程车";
    self.view.backgroundColor = BacksColor;
    self.navigationController.navigationBar.translucent = NO;
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-55*displaywidth-SCREER_HeiX) style:UITableViewStylePlain];
    _tableview.backgroundColor = BacksColor;
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
    UIButton *soureBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, SCREEN_HEIGHT-STA_NAV_HEIGHT- 55*displaywidth-SCREER_HeiX, SCREEN_WIDTH-30*displaywidth, 45*displaywidth) ImageName:nil Target:self Action:@selector(soureBtnAction) Title:@"立即发布" Font:16.0];
    soureBtn.backgroundColor = RGB(255, 153, 0);
    [soureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    soureBtn.layer.cornerRadius = 5;
    soureBtn.layer.masksToBounds = YES;
    [self.view addSubview:soureBtn];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1)
    {
        return 3;
    }
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0)
    {
        NSArray *imgAry = @[@"congicon",@"huiicon"];
        UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 17.5*displaywidth, 20*displaywidth, 25*displaywidth) ImageName:imgAry[indexPath.row]];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        [cell.contentView addSubview:imgView];
        NSArray *textAry = @[_shipmentText,_destinationText];
        NSArray *pladerAry = @[_shipmentID,_destinationID];
        UILabel *textLab = [ZCControl createLabelWithFrame:CGRectMake(50*displaywidth, 10*displaywidth, SCREEN_WIDTH-80*displaywidth, 40*displaywidth) Font:17.0 Text:textAry[indexPath.row] Color:RGB(204, 204, 204)];
        if (![pladerAry[indexPath.row] isEqualToString:@""])
        {
            textLab.textColor = BlaTitColor;
        }
        [cell.contentView addSubview:textLab];
        if (indexPath.row == 0)
        {
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(50*displaywidth, 59*displaywidth, SCREEN_WIDTH-65*displaywidth, 1*displaywidth)];
            lineView.backgroundColor = RGB(204, 204, 204);
            [cell.contentView addSubview:lineView];
        }
        UIImageView *imgV = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH-30*displaywidth, 20*displayheight, 15*displaywidth, 20*displayheight) ImageName:@"gs_icon05"];
        imgV.contentMode = UIViewContentModeScaleAspectFit;
        [cell.contentView addSubview:imgV];
    }
    else
    {
        if (indexPath.row != 2)
        {
            UIView *lineBView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10*displaywidth)];
            lineBView.backgroundColor = BacksColor;
            [cell.contentView addSubview:lineBView];
            NSArray *nameAry = @[@"返程日期",@"返程时间"];
            NSArray *timeAry = @[_dayStr,_timeStr];
            UILabel *titLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 10*displaywidth, 80*displaywidth, 50*displaywidth) Font:15.0 Text:nameAry[indexPath.row] Color:BlaTitColor];
            [cell.contentView addSubview:titLab];
            UILabel *timeLab = [ZCControl createLabelWithFrame:CGRectMake(95*displaywidth, 20*displaywidth, SCREEN_WIDTH-185*displaywidth, 30*displaywidth) Font:13.0 Text:timeAry[indexPath.row] Color:RGB(178, 178, 178)];
            timeLab.textAlignment = NSTextAlignmentLeft;
            [cell.contentView addSubview:timeLab];
            UIImageView *imgV = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH-30*displaywidth, 25*displayheight, 15*displaywidth, 20*displayheight) ImageName:@"gs_icon05"];
            imgV.contentMode = UIViewContentModeScaleAspectFit;
            [cell.contentView addSubview:imgV];
        }
        else
        {
            cell.backgroundColor = BacksColor;
            NSString *imgStr = @"gouxuan1";
            if (_isGx)
            {
                imgStr = @"gouxuan2";
            }
            UIButton *gouXuan = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, 15*displaywidth, 200*displaywidth, 20*displaywidth) ImageName:imgStr Target:self Action:@selector(gouxuanAction:) Title:@" 承诺此信息真实，不虚假" Font:12.0];
            [gouXuan setTitleColor:RGB(174, 174, 174) forState:UIControlStateNormal];
            gouXuan.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            gouXuan.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            NSString *content = gouXuan.titleLabel.text;
            UIFont *font = gouXuan.titleLabel.font;
            CGSize size = CGSizeMake(MAXFLOAT, 20*displaywidth);
            CGSize buttonSize = [content boundingRectWithSize:size
                                                      options:NSStringDrawingTruncatesLastVisibleLine  | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                   attributes:@{ NSFontAttributeName:font}
                                                      context:nil].size;
            gouXuan.frame = CGRectMake(15*displaywidth, 15*displaywidth, buttonSize.width+30*displaywidth, 20*displaywidth);
            [cell.contentView addSubview:gouXuan];
            UIButton *xzBtn = [ZCControl createButtonWithFrame:CGRectMake(buttonSize.width+45*displaywidth, 15*displaywidth, 100*displaywidth, 20*displaywidth) ImageName:nil Target:self Action:@selector(xieyiAction) Title:@"《发布须知》" Font:12.0];
            [xzBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
            xzBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            xzBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            [cell.contentView addSubview:xzBtn];
        }
        
    }
    return cell;
}

- (void)gouxuanAction:(UIButton *)btn
{
    _isGx = !_isGx;
    NSString *imgStr = @"gouxuan1";
    if (_isGx)
    {
        imgStr = @"gouxuan2";
    }
    [btn setImage:IMAGE(imgStr) forState:UIControlStateNormal];
    [btn setTitle:@" 承诺此信息真实，不虚假" forState:UIControlStateNormal];
}

//发布须知
- (void)xieyiAction
{
    ReleaseNotesViewController *vc = [[ReleaseNotesViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WEAKSELF;
    NSInteger section = indexPath.section;
    NSInteger index = indexPath.row;
    if (section == 0)
    {
        CloseGoodsAddressViewController *vc = [[CloseGoodsAddressViewController alloc] init];
        vc.areaType = index;
        vc.isPush = YES;
        vc.closeBlock = ^(NSString *name, NSInteger index)
        {
            NSArray *nameAry = [name componentsSeparatedByString:@","];
            if (nameAry.count == 2)
            {
                if (index == 0)
                {
                    _shipmentText = nameAry[0];
                    _shipmentID = nameAry[1];
                }
                else
                {
                    _destinationText = nameAry[0];
                    _destinationID = nameAry[1];
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
            });
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        if (indexPath.row == 0)
        {
            NSString *str = _dayStr;
            if ([_dayStr isEqualToString:@""])
            {
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                [formatter setDateFormat:@"YYYY-MM-dd"];
                NSDate *datenow = [NSDate date];
                NSString *currentTimeString = [formatter stringFromDate:datenow];
                str = currentTimeString;
                
            }
            [self.pickerView appearWithTitle:@"年月日" pickerType:GSPickerTypeDatePicker subTitles:nil selectedStr:str sureAction:^(NSInteger path, NSString *pathStr) {
                weakSelf.dayStr = pathStr;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.tableview reloadData];
                });
                [weakSelf.tableview reloadData];
            } cancleAction:^{
                
            }];
        }
        else if (indexPath.row == 1)
        {
            if (!self.datePickerView)
            {
                DateTimePickerView *pickerView = [[DateTimePickerView alloc] init];
                pickerView.delegate = self;
                pickerView.pickerViewMode = DatePickerViewTimeMode;
                [sharedDelegate.window addSubview:pickerView];
                self.datePickerView = pickerView;
            }
            NSString *hours = @"0";
            NSString *min = @"0";
            if (![_timeStr isEqualToString:@""])
            {
                NSArray *timeArray = [_timeStr componentsSeparatedByString:@":"];
                if (timeArray.count == 2)
                {
                    hours = timeArray[0];
                    min = timeArray[1];
                }
            }
            self.datePickerView.hours = hours;
            self.datePickerView.minus = min;
            [self.datePickerView showDateTimePickerView];
           
        }
    }
}

- (void)didClickFinishDateTimePickerView:(NSString *)date
{
    _timeStr = date;
    [_tableview reloadData];
}

- (GSPickerView *)pickerView{
    if (!_pickerView) {
        _pickerView = [[GSPickerView alloc]initWithFrame:self.view.bounds];
    }
    return _pickerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60*displaywidth;
}

//立即发布
- (void)soureBtnAction
{
    NSArray *nameARRAY = @[_shipmentID,_destinationID,_dayStr,_timeStr];
    NSArray *tostAry = @[@"请选择将要卸货的地址",@"请选择将要返回的地址",@"请选择返程日期",@"请选择返程时间"];
    for (int i = 0; i < nameARRAY.count; i++)
    {
        if ([nameARRAY[i] isEqualToString:@""])
        {
            [LTools showMBProgressWithText:tostAry[i] addToView:self.view];
            return;
        }
    }
    if (!_isGx)
    {
        [LTools showMBProgressWithText:@"请勾选承诺信息" addToView:self.view];
        return;
    }
    WEAKSELF;
    NSDictionary *dic = @{@"shipment.id":_shipmentID,
                          @"shipmentText":_shipmentText,
                          @"destination.id":_destinationID,
                          @"destinationText":_destinationText,
                          @"returnDtm":[NSString stringWithFormat:@"%@ %@:00",_dayStr,_timeStr]};
    [HYBaseHandler requestWithTheFormUrl:SERVER_ReleaseCarSave Parmers:dic Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             [LTools showMBProgressWithText:@"发布成功" addToView:sharedDelegate.window];
             [self.navigationController popViewControllerAnimated:YES];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         
     }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
